<?php

include_once 'Session.fitcoders.php';

class entity_dao {

    /**
     * Devuelve una solo registro.
     * @param type $SQL INGRESA UN SELECT COUNT(*) FROM ENTITY;
     * @return type
     */
    public function countSQL($SQL) {
        $db = new Session();
        $count = $db->executeScalar($SQL, null);
        $db->closeSession();

        return $count;
    }
    
    /**
     * ELIMINA POR EL id ENCONTRADO EN LA ENTIDAD
     * @param type $object
     */
    public function deleteModel($object) {
        $sql = "DELETE FROM {TABLE} WHERE id=?";
        $sql = str_replace("{TABLE}", $object->table(), $sql);
        if (!$object->getId()) {
            $db = new Session();
            $db->execute($sql, array($object->getId()));
            $db->closeSession();
        }
    }

    public function listSqlToArray($sql, $params = null) {
        $db = new Session();
        $array = $db->execute($sql, $params);        
        $db->closeSession();
        
        return $array;
    }
    
    public function listToJSON($sql, $params = null) {
        $db = new Session();
        $array = $db->dataJSON($sql, $params);        
        $db->closeSession();
        
        return $array;
    }


    public function saveModel($object) {
        $sql = "INSERT INTO {TABLE} ({FIELDS}) VALUES ({SIGNES})";
        $sql = str_replace("{TABLE}", $object->table(), $sql);
        $sql = str_replace("{FIELDS}", $object->fieldsToString(), $sql);
        $sql = str_replace("{SIGNES}", $object->signesToSave(), $sql);
        
        $db = new Session();
        $db->execute($sql, $object->paramsToSave());
        $id = $db->executeScalar("SELECT LAST_INSERT_ID()");
        $db->closeSession();

        return $id;
    }

    public function updateModel($object) {
        $sql = "UPDATE {TABLE} SET {SIGNES} WHERE id=?";
        $sql = str_replace("{TABLE}", $object->table(), $sql);
        $sql = str_replace("{SIGNES}", $object->signesToUpdate(), $sql);
        
        $db = new Session();
        $db->execute($sql, $object->paramsToUpdate());
        $db->closeSession();
    }
    
    public function updateSQL($sql, $params = null) {
        $db = new Session();
        $db->execute($sql, $params);
        $db->closeSession();
    }

}
?>

